import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import React, { useState, useEffect } from "react";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IEditorConfig } from "@wangeditor/editor";
import { Button, PageHeader, Modal, Form, Input, Spin, message } from "antd";
import dayjs from "dayjs";
import "./less/edit.less";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { addArticle, getArticleById } from "../network/api";

export default function Edit() {
  const [editor, setEditor] = useState(null); // 存储 editor 实例
  const [loading, setLoading] = useState(false);
  const [html, setHtml] = useState(""); // 编辑器内容
  // 弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
  let params = useParams();
  let location = useLocation();
  let curDate = dayjs().format("YYYY-MM-DD");
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const toolbarConfig = {};
  const editorConfig = { placeholder: "请输入内容..." };

  const getArticleByIdDone = async (id) => {
    const result = await getArticleById(params.id);
    if (!result.errCode) {
      message.success("获取成功");
      setHtml(result.data.content);
      let { title, subTitle } = result.data;
      onFill({ title, subTitle });
    }
  };
  // 及时销毁 editor ，重要！
  useEffect(() => {
    if (params.id) {
      getArticleByIdDone(params.id);
    }
    return () => {
      if (editor == null) return;
      editor.destroy();
      //获取文章
    };
  }, []);
  //提交表单
  const handleOk = () => {
    form
      .validateFields()
      .then((values) => {
        setIsModalVisible(false);
        addArticleHandle({ ...values, content: html });
        form.resetFields();
        navigate("/list");
      })
      .catch((info) => {
        return;
      });
  };
  const handleCancel = () => {
    if (!params.id) {
      form.resetFields();
    }

    setIsModalVisible(false);
  };
  // 填充表单数据
  const onFill = ({ title, subTitle }) => {
    form.setFieldsValue({
      title: title,
      subTitle: subTitle,
    });
  };
  //添加文章请求
  const addArticleHandle = async (data) => {
    try {
      setLoading(true);
      const result = await addArticle(data);
      if (!result.errCode) {
        message.success(result.message);
      }
    } catch (error) {}
    setLoading(false);
  };
  return (
    <Spin spinning={loading}>
      <div className="edit-box">
        <div style={{ border: "1px solid #ddd", zIndex: 100 }}>
          <div className="edit-header">
            <PageHeader
              className="site-page-header"
              onBack={params.id ? () => navigate(-1) : null}
              title="文章编辑"
              subTitle={"当前时间: " + curDate}
            />
            <Button type="primary" onClick={() => setIsModalVisible(true)}>
              提交文章
            </Button>
          </div>
          <Toolbar
            editor={editor}
            defaultConfig={toolbarConfig}
            mode="default"
            style={{ borderBottom: "1px solid #ddd" }}
          />
          <Editor
            defaultConfig={editorConfig}
            value={html}
            onCreated={setEditor}
            onChange={(editor) => setHtml(editor.getHtml())}
            mode="default"
            style={{ height: "500px", overflow: "hidden" }}
          />
        </div>
        <>
          <Modal
            title="提交文章"
            cancelText="取消"
            okText="提交"
            zIndex={99999}
            visible={isModalVisible}
            onOk={handleOk}
            onCancel={handleCancel}
          >
            <Form
              name="basic"
              form={form}
              labelCol={{
                span: 3,
              }}
              wrapperCol={{
                span: 21,
              }}
              initialValues={{
                remember: true,
              }}
              autoComplete="off"
            >
              <Form.Item
                label="标题"
                name="title"
                rules={[
                  {
                    required: true,
                    message: "请输入标题!",
                  },
                ]}
              >
                <Input />
              </Form.Item>

              <Form.Item label="副标题" name="subTitle">
                <Input />
              </Form.Item>
            </Form>
          </Modal>
        </>
      </div>
    </Spin>
  );
}
